package com.milhouz.findmydroid.db;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import au.com.bytecode.opencsv.CSVReader;

public class DbLoaderASyncTask extends AsyncTask<Integer, Integer, Long> {

	private final Context mContext;

	public DbLoaderASyncTask(Context context) {
		mContext = context;
	}

	@Override
	protected Long doInBackground(Integer... nbCards) {
		loadCards();
		return 0l;
	}

	private void loadCards() {
		Log.i(AppConstants.TAG, "First data loading");

		// Load data from csv file
		try {
			// Parse the CSV
			CSVReader reader = new CSVReader(new InputStreamReader(mContext.getAssets().open(AppConstants.CSV_QUESTIONS_FILE), "UTF-8"), ',');
			String[] nextLine;

			ContentValues values = new ContentValues();
			int csvLineNumber = 0;
			int curCategoryId = 1;
			while ((nextLine = reader.readNext()) != null) {
				// Save category if exists
				curCategoryId = saveCategoryAndGetId(nextLine[0]);
				// Save the current line
				values.clear();
				values.put(AppConstants.COLUMN_NAME, nextLine[1]);
				values.put(AppConstants.COLUMN_LANG, nextLine[2]);
				// values.put(Constants.COLUMN_DESCRIPTION, nextLine[3]);
				values.put(AppConstants.COLUMN_IS_USER, "0");
				values.put(AppConstants.COLUMN_CATEGORY_ID, curCategoryId);
				mContext.getContentResolver().insert(AppProvider.CHARACTERS_URI, values);
				csvLineNumber++;
			}
		} catch (FileNotFoundException e) {
			Log.e(AppConstants.TAG, "Cards file not found", e);
		} catch (IOException e) {
			Log.e(AppConstants.TAG, "Error during file reading", e);
		} finally {
			Log.i(AppConstants.TAG, "Data loading finished.");
		}
	}

	private int saveCategoryAndGetId(String categoryName) {
		int id = AppDbAPI.getInstance().getCategoryId(mContext, categoryName);
		if (id == -1) {
			ContentValues values = new ContentValues();
			values.put(AppConstants.COLUMN_NAME, categoryName);
			mContext.getContentResolver().insert(AppProvider.CATEGORIES_URI, values);
			return id;
		}
		return id;
	}

}
